package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;
/**
 * CRM系统已经导入Spring data Jpa 什么意思		???
 * 
 * @author ZYK
 *
 */
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
	
	@Autowired
	private CustomerRepository customerRepository;
	
	@Override
	public List<Customer> findNoAssociationCustomers() {
		//fixedAreaId is null
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		//fixedAreaId is ?
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
		//解除关联动作	一刀切做法,将原来fixedAreaId的所有客户的定区id置为空,再将选中客户的fixedAreaId字段设为传进来的fixedAreaId的值
		customerRepository.clearFixedAreaId(fixedAreaId);
		
		if(StringUtils.isBlank(customerIdStr)){
			//没有选中客户,退出操作
			return;	//相当于事务回滚
		}
		
		//切割字符串1,2,3
		String[] customerArray = customerIdStr.split(",");
		for (String idStr : customerArray) {
			Integer id = Integer.parseInt(idStr);
			customerRepository.updateFixedArea(fixedAreaId,id);
		}

	}
}
